# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: jhkim

import os
import pandas
from absl import app, flags

import coin.strategy.mm.tool.archive_base as abase

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

from sqlalchemy import create_engine


def _gen_engine():
  engine = create_engine(
      "mysql://pta_querier:0C3n5szBUEhn@coin-db.corp.prestolabs.io/pta_stats_20190513",
      echo=False)
  return engine


def main(_):
  tdates = abase.get_trading_dates(flags.FLAGS.trading_date)
  engine = _gen_engine()

  tdstr_from = tdates[0].strftime("%Y%m%d")
  tdstr_to = tdates[-1].strftime("%Y%m%d")

  sql = f"""select * from StrategyPnlDetailView
where trading_date >= '{tdstr_from}' and trading_date <= '{tdstr_to}'
and strategy_name like '{flags.FLAGS.pattern.replace("%", "%%")}'
and pnl_type = "from_balance"
"""
  print(sql)
  df = pandas.read_sql(sql, engine)
  df = df[['ts', 'pnl', 'strategy_name', 'accounting_currency', 'trading_date']]
  df['dti'] = pandas.DatetimeIndex(df['ts'])
  df['hour'] = df['dti'].dt.hour

  plt.rcParams['lines.linewidth'] = 0.5
  plt.rcParams['figure.figsize'] = 8, 4
  plt.rcParams['font.size'] = 10
  plt.rcParams['legend.fontsize'] = 10
  plt.rcParams['xtick.labelsize'] = 10
  plt.rcParams['ytick.labelsize'] = 10

  out_dir = f"{flags.FLAGS.out_dir}/{flags.FLAGS.trading_date}"
  os.makedirs(out_dir, exist_ok=True)
  for currency, currencydf in df.groupby('accounting_currency'):
    if currency == '':
      continue
    seri = currencydf.groupby('hour').sum()['pnl']
    plt.plot(seri, '.-', lw=0.5, markersize=2)
    plt.title(f"hourly pnl {flags.FLAGS.trading_date} {flags.FLAGS.pattern} {currency}")
    plt.grid()
    plt.savefig(f"{out_dir}/hourly_{flags.FLAGS.trading_date}_{flags.FLAGS.pattern}_{currency}.png")
    plt.close()

    seri = currencydf[currencydf['hour'] == 23].groupby('trading_date').sum().cumsum()['pnl']
    plt.plot(seri, '.-', lw=0.5, markersize=2)
    plt.title(f"daily pnl {flags.FLAGS.trading_date} {flags.FLAGS.pattern} {currency}")
    plt.grid()
    plt.savefig(f"{out_dir}/daily_{flags.FLAGS.trading_date}_{flags.FLAGS.pattern}_{currency}.png")
    plt.close()


if __name__ == '__main__':
  flags.DEFINE_string('pattern', '%', '')
  flags.DEFINE_string('out_dir', 'hourly_pnl', '')
  flags.DEFINE_string('trading_date', None, '')
  app.run(main)
